<?php

namespace App\Http\Controllers;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;


class LoginController extends WxController {
	public function miniappLogin(Request $request) {
        $config = config("wechat.mini_program.default");
        $app = Factory::miniProgram($config);
        $res = $app->auth->session($request['code']);
        session('session_key',$res['session_key']);
        //获取手机号
        $iv = $request['iv'];
        $user_id = isset($request['user_id']) ? $request['user_id'] : 0;
        $encryptedData = $request['encryptedData'];
        $decryptedData = $app->encryptor->decryptData($res['session_key'], $iv, $encryptedData);
        $phone = $decryptedData['phoneNumber'];
        if (isset($res['openid'])) {
            $user = User::where("openid", $res['openid'])->first();
            if (empty($user)) {
                $user = new User();
                $user->token = User::makeToken($res['openid']);
                $user->mobile = $phone;
                $user->nickname = '';
                $user->avatar = '';
                $user->openid = $res['openid'];
                $user->created_at = time();
                $user->save();
            }
            return $this->success($user);
        }
	}
}